package controller;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

import android.app.Activity;
import android.util.Log;
import android.widget.Toast;

public abstract class Controller  extends Thread{

	
	public static final int DEFAULTPORT = 2011;
	public static final String DEFAULIP = "192.168.1.101";
	public static final int BEGIN = 1;
	public static final int WAITSTART = 2;
//	public static final int GAMEEXIT = 0;
	public static final int ACTIVE = 5;
//	public static final int INACTIVE = 6;
//	public static final int ENDGAME = 7;
	private int currentState ;
	
	
	
	
	/**--------------------------------------------------------------
	 * **************** START  **************************************
	 **-------------------------------------------------------------*/
    @Override
    public void run(){
      	Log.i("service state", "started..........");
        currentState = BEGIN;
        while(true){
            while(in.hasNext()){
                String response = in.nextLine();
                Log.i("service","+-------------------RUN----------------------------+");
                Log.i("service","+-------STATE     "+currentState);
                Log.i("service","+-------RESPONSE  "+response);
                Log.i("service","+--------------------------------------------------+");
                processResponse(response);
            }
        }
    }



        /**--------------------------------------------------------------
	 * **************** Controller  *********************************
	 **-------------------------------------------------------------*/
	public void processResponse(String rcv){
            
                switch( currentState){

                /**-------------------------------------------------------
                 * ************ BEGIN STATE ******************************
                 **------------------------------------------------------*/
                case BEGIN:
                        if(rcv.startsWith("fail")){			// Response login fail from server

                                Log.i("begin state","Login Fail!");
                                Log.i("begin state","System going shutdown...");
                                noticeLoginFail();
                                System.exit(0);
                        }

                        if(rcv.startsWith("updateuser")){
                                currentState = WAITSTART;
                                startUpUi();
                                Log.i("begin state", "updateuser");
                                setUpdateUser(rcv);
                        }

                	break;


//                /**-------------------------------------------------------
//                 * ************ WAITSTART STATE **************************
//                 **------------------------------------------------------*/
//
//                case WAITSTART:{
//
//                        if(rcv.startsWith("updateuser")){
//                                setUpdateUser(rcv);
//                        }
//                        /** -3*/
//                        if(rcv.startsWith("fail")){         // Response start fail from server
//                                reStartGame();                  // Call RestartGame function
//                        }
//
//                        /** -4*/
//                        if(rcv.startsWith("start")){        // Response start Session
//                                currentState = ACTIVE;          // Message format start active_userId time_length
//                                setUpSession(rcv);
//                        }
//
//                        /** -5*/
//                        if(rcv.startsWith("wait")){         // Response wait Session
//                                currentState = INACTIVE;		// Message format wait  active_userId time_length
//                                setUpSession(rcv);
//                        }
//
//                        /** -7*/
//                        if(rcv.startsWith("chat")){         // Response wait Session
//                                setUpChatMessage(rcv);			// Call Set Chat Message
//                        }
//                }
//                break;
//
//
                /**-------------------------------------------------------
                 * ************ ACTIVE STATE *****************************
                 **------------------------------------------------------*/
                case ACTIVE:{

//                        /** -2*/
//                        if( rcv.startsWith("selectedimg")){      // response message:  selectedimg active_user_score imgId iconId ismatch isbonus
//                                setSelectedImg(rcv);			// Call Function setSelectedImg
//                        }
//
//                        /** -3*/
//                        if( rcv.startsWith("updateuser")){	    // Response Update User from Server
//                                setUpdateUser(rcv);             // Call Function setUpdateUser
//                        }
//
//                        /** -4*/
//                        if(rcv.startsWith("wait")){                     // Response wait Session
//                                currentState = INACTIVE;		// Message format wait  active_userId time_length
//                                setUpSession(rcv);
//                        }
//
//                        /** -5*/
//                        if(rcv.startsWith("win")){
//                                currentState = ENDGAME;
//                                endGame(rcv);
//
//                        }
//
//                        /** -7*/
//                        if(rcv.startsWith("chat")){         // Response wait Session
//                                setUpChatMessage(rcv);			// Call Set Chat Message
//                        }

                }
                break;
//
//
//                /**-------------------------------------------------------
//                 * ************ INACTIVE STATE ***************************
//                 **------------------------------------------------------*/
//                case INACTIVE:{
//
//                        /** -1*/
//                        if( rcv.startsWith("selectedimg")){
//                                setSelectedImg(rcv);			// Call Function setSelectedImg
//                        }
//
//                        /** -2*/
//                        if(	rcv.startsWith("updateuser")){	// Response Update User from Server
//                                setUpdateUser(rcv);             // Call Function setUpdateUser
//                        }
//
//                        /** -3*/
//                        if(rcv.startsWith("start")){        // Response start Session
//                                currentState = ACTIVE;          // Message format start active_userId time_length
//                                setUpSession(rcv);
//                        }
//
//
//                        /** -4*/
//                        if(rcv.startsWith("wait")){                     // Response wait Session
//                                currentState = INACTIVE;		// Message format wait  active_userId time_length
//                                setUpSession(rcv);
//                        }
//
//                        /** -5*/
//                        if(rcv.startsWith("win")){
//                                currentState = ENDGAME;
//                                endGame(rcv);
//
//                        }
//
//                        /** -7*/
//                        if(rcv.startsWith("chat")){         // Response wait Session
//                                setUpChatMessage(rcv);			// Call Set Chat Message
//                        }
//
//
//                }
//                break;
//
//                /**-------------------------------------------------------
//                 * ************ EXITGAME STATE ********************************
//                 **------------------------------------------------------*/
//                default:{
//                	    Log.i("exit state","System going shutdown...");
//                        System.exit(0);
//
//                }
//                break;
                }
	}
private void noticeLoginFail() {
			// TODO Auto-generated method stub
			
		}



	
	

	public void sendMessage(String message) {
		Log.i("sent message","Sending...with ms: "+message);
		String ms = "chat" +" "+message;
		try {
			outToServer.writeBytes(ms+"\n");
			outToServer.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
//
//
//
//	public void setUpChatMessage(String rcv) {
//		// TODO Auto-generated method stub
//		
//	}
//
//
//
//	public void endGame(String rcv) {
//	}
//
//	public void setUpSession(String rcv) {
//		// TODO Auto-generated method stub
//		
//	}
//
//
//
//	public void reStartGame() {
//		// TODO Auto-generated method stub
//		
//	}


	public void startUpUi() {
		// TODO Auto-generated method stub
		Log.i("controller", "aaa");
	}


//	public void setSelectedImg(String rcv) {
//		// TODO Auto-generated method stub
//		
//	}


	public void selectImage(int imgId) {
		// TODO Auto-generated method stub
		String ms = "selectimg" + " "+ imgId;
		
		
		try {
			outToServer.writeBytes(ms+"\n");
			outToServer.flush();
			System.out.println(ms);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}


	public void startGame() {
		String ms = "startgame";
		Log.i("288", "String ms =startgame");
		try {
			if(outToServer == null)
				Log.i("290", "outToServer == null");
			outToServer.writeBytes(ms+"\n");
			outToServer.flush();
			//Game.delay_imt_thread.start();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		
	}



	public void setUpdateUser(String rcv) {
		// TODO Auto-generated method stub
	}
	
	public void login(String userId) {		
			Log.i("login state","Loging...with user: "+userId);
			String ms = "login" +" "+userId;
			try {
				outToServer.writeBytes(ms+"\n");
				outToServer.flush();
			} catch (IOException e) {

				Log.i("login state","IO error!, cannot login now!");
			}
	}
	
	public void connect(String ip, int port){
		
		try {
			clientSocket = new Socket(ip,port);
			outToServer = new DataOutputStream(clientSocket.getOutputStream());
            in = new Scanner(clientSocket.getInputStream());
            Log.i("connect state","Connected to server "+ip + "- port "+port);
             
		} catch (UnknownHostException e) {
			Log.i("connect state","Unknow Host: "+ip + " port: "+port);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void exitGame() {
		try{

			outToServer.writeBytes("logout\n");
			outToServer.flush();
			fromClient.close();
			outToServer.close();
			clientSocket.close();
		
		}catch(IOException e)
		{
			Log.i("exit state","Error! Logout ");
		}
		
		Log.i("exit state","game is exiting....");
        System.exit(0);
	}
	
	public void setCurrentState(int state) {
		this.currentState = state;
	}


	public int getCurrentState() {
		return currentState;
	}

	private Socket clientSocket = null;
	private	DataOutputStream outToServer = null;
    private Scanner in;
	private BufferedReader fromClient = new BufferedReader(new InputStreamReader(System.in));
	
}



